Skip to content

Conversation

z33ky
Copy link

@z33ky z33ky commented Nov 21, 2020

I'm proposing to add the methods find_or_{first,nth,last} to the Iterator trait, to facilitate returning an item that is part of the sequence itself in case no item satisfies the predicate.

Example:

let a = [0, 1, 2, 3];

assert_eq!(a.iter().by_ref().copied().find_or_first(|e| *e == 5   ), Some(0)); // predicate is never satisfied, so `find_or_first` returns the first item (`0`)
assert_eq!(a.iter().by_ref().copied().find_or_nth(  |e| *e == 5, 1), Some(1)); // predicate is never satisfied, so `find_or_nth` returns the 2nd item (`1`) (count begins from `0`)
assert_eq!(a.iter().by_ref().copied().find_or_last( |e| *e == 5   ), Some(3)); // predicate is never satisfied, so `find_or_last` returns the last item (`3`)

Rendered

# Drawbacks
[drawbacks]: #drawbacks

libstd grows.
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I hope this isn't too terse, but that's literally all that'd happen I think.

@sfackler
Copy link
Member

Small API additions do not require RFCs. You can just make a PR against rust-lang/rust with the proposed methods.

@z33ky
Copy link
Author

z33ky commented Nov 21, 2020

Thanks, I opened rust-lang/rust#79271.

@z33ky z33ky closed this Nov 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants